package com.realbrand.net.realbrandpay.ui.activity.wallet.set;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.IProvingAccount;
import com.realbrand.net.realbrandpay.inter.IVerifyAuthCode;
import com.realbrand.net.realbrandpay.ui.activity.login.ChangeLoginPasswdActivity;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2017/9/11.
 */

public class ChangePayPasswdVerifyActivity extends BaseActivity {
    @BindView(R.id.changePasswdVerify_toolbar)
    Toolbar changePasswdVerifyToolbar;
    @BindView(R.id.changePasswdVerify_tv_text)
    TextView changePasswdVerifyTvText;
    @BindView(R.id.changePasswdVerify_et_VerifyCode)
    EditText changePasswdVerifyEtVerifyCode;
    @BindView(R.id.changePasswdVerify_bt_sendPhoneCode)
    Button changePasswdVerifyBtSendPhoneCode;
    @BindView(R.id.changePasswdVerify_tv_toPasswd)
    TextView changePasswdVerifyTvToPasswd;
    @BindView(R.id.changePasswdVerify_bt_next)
    Button changePasswdVerifyBtNext;

    //用户手机号码
    private String userMobile;

    //定时器
    private TimeCount time;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        changePasswdVerifyToolbar.setTitle("");
        changePasswdVerifyToolbar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(changePasswdVerifyToolbar);
        changePasswdVerifyToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ChangePayPasswdVerifyActivity.this, PasswordManageActivity.class));
                finish();
            }
        });
        SpannableString ss = new SpannableString("请输入旧密码");//定义hint的值
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(16,true);//设置字体大小 true表示单位是sp
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        changePasswdVerifyEtVerifyCode.setHint(new SpannedString(ss));
        //获取用户手机号码
        SharedPreferences userMassage = getSharedPreferences("userMassage", MODE_PRIVATE);
        userMobile = userMassage.getString("mobile", "");
        changePasswdVerifyTvText.setText("请输入" + userMobile + "收到的短信验证码");
        setOnClick();
        time = new TimeCount(120000, 1000);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.changepaypasswdverify_activity;
    }

    @Override
    protected void setOnClick() {
        changePasswdVerifyBtSendPhoneCode.setOnClickListener(this);
        changePasswdVerifyBtNext.setOnClickListener(this);
        changePasswdVerifyTvToPasswd.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //获取验证码
            case R.id.changePasswdVerify_bt_sendPhoneCode:
                getVerifyCode();
                break;
            //下一步
            case R.id.changePasswdVerify_bt_next:
                //先获取用户输入的验证码
                String codeByUser = changePasswdVerifyEtVerifyCode.getText().toString();
                //判断用户输入的验证码是否为空
                if (codeByUser == null) {
                    Static.toast(this, "请输入手机收到的验证码");
                } else {
                    changPasswdverify(codeByUser);
                }
                break;
            //切换到密码验证
            case R.id.changePasswdVerify_tv_toPasswd:
                startActivity(new Intent(this, ChangePayPasswdActivity.class));
                finish();
                break;
        }
    }

    private void changPasswdverify(String codeByUser) {
        JSONObject object = new JSONObject();
        try {
            object.put("METHOD", "VerifyAuthCode");
            object.put("SOURCE", "PhoneLoginActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "1");
            object.put("INDEX", Static.getDay());
            object.put("UserMobile", userMobile);
            object.put("Verification", codeByUser);
            L.d(L.TAG,"修改密码传过去的验证码"+codeByUser);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, object.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IVerifyAuthCode iVerifyAuthCode = retrofit.create(IVerifyAuthCode.class);
            Call<ResponseBody> call = iVerifyAuthCode.verifyAuthCode(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response == null) {
                        Static.toast(ChangePayPasswdVerifyActivity.this, "网络繁忙");
                    } else {
                        try {
                            String result = response.body().string();
                            L.d(L.TAG, "修改密码验证返回结果" + result);
                            try {
                                JSONObject json = new JSONObject(result);
                                JSONArray data = json.getJSONArray("DATA");
                                JSONObject dataJSONObject = data.getJSONObject(0);
                                String string = dataJSONObject.getString("result");
                                if ("true".equals(string)) {
                                    //表示验证成功
                                    startActivity(new Intent(ChangePayPasswdVerifyActivity.this, PayPasswdChangeActivity.class));
                                    finish();
                                } else if ("验证码已过时".equals(string)) {
                                    Static.toast(ChangePayPasswdVerifyActivity.this, "验证码已过时，请重新获取验证码");
                                } else if ("验证码错误".equals(string)) {
                                    Static.toast(ChangePayPasswdVerifyActivity.this, "验证码错误，请重新输入验证码");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getVerifyCode() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("METHOD", "AccountProving");
            jsonObject.put("SOURCE", "PhoneLoginActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "1");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("UserMobile", userMobile);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            Retrofit retrofit = new Retrofit.Builder().baseUrl(HTTPAPI.BASE_URL).build();
            IProvingAccount iGetCode = retrofit.create(IProvingAccount.class);
            Call<ResponseBody> code = iGetCode.getCode(body);
            code.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response == null) {
                        Static.toast(ChangePayPasswdVerifyActivity.this, "网络繁忙，请稍后再试。。。");
                    } else {
                        try {
                            String result = response.body().string();
                            L.d(L.TAG, "jieguo" + result);
                            try {
                                JSONObject object = new JSONObject(result);
                                JSONArray data = object.getJSONArray("DATA");
                                JSONObject dataJSONObject = data.getJSONObject(0);
                                String string = dataJSONObject.getString("result");
                                if ("false".equals(string)) {
                                    Static.toast(ChangePayPasswdVerifyActivity.this, "该手机号码未注册");
                                } else if ("true".equals(string)) {
                                    time.start();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            changePasswdVerifyBtSendPhoneCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
            changePasswdVerifyBtSendPhoneCode.setClickable(false);
            changePasswdVerifyBtSendPhoneCode.setText(millisUntilFinished / 1000 + "s后可重发");
        }

        @Override
        public void onFinish() {
            changePasswdVerifyBtSendPhoneCode.setText("重新获取验证码");
            changePasswdVerifyBtSendPhoneCode.setClickable(true);
            changePasswdVerifyBtSendPhoneCode.setBackground(getResources().getDrawable(R.drawable.bt_regist));
        }
    }
}
